import { Controller } from "egg";
import { UserProps } from "../model/user";

const userCreateRules = {
  username: "email",
  password: { type: "password", min: 8 },
};

export default class UserController extends Controller {
  async createByEmail() {
    const { ctx, service, app } = this;
    // ctx.validate(userCreateRules)
    const errors = this.validateUserInput();
    if (errors) {
      return ctx.helper.error({ ctx, errorType: "userValidateFail", error: errors });
    }

    const { username } = ctx.request.body;
    const user = await service.user.findByUsername(username);
    if (user) {
      return ctx.helper.error({ ctx, errorType: "createUserAlreadyExists" });
    }

    const userData = await service.user.createByEmail(ctx.request.body);
    ctx.helper.success({ ctx, res: userData });
  }

  validateUserInput() {
    const { ctx, app } = this;
    const errors = app.validator.validate(userCreateRules, ctx.request.body);
    return errors;
  }

  async loginByEmail() {
    const { ctx, service, app } = this;
    // 检查用户输入
    const error = this.validateUserInput();
    if (error) {
      return ctx.helper.error({ ctx, errorType: "userValidateFail", error });
    }

    // 获取用户信息
    const { username, password } = ctx.request.body;
    const user = await service.user.findByUsername(username);
    // 检查用户是否存在
    if (!user) {
      return ctx.helper.error({ ctx, errorType: "loginCheckFailInfo" });
    }
    // 验证密码是否成功
    const verifPwd = await ctx.compare(password, user.password);
    if (!verifPwd) {
      return ctx.helper.error({ ctx, errorType: "loginCheckFailInfo" });
    }

    /* const userObj: Partial<UserProps> = user.toJSON();
    delete userObj.password;
    delete userObj.__v; */
    // ctx.cookies.set("username", user.username, { encrypt: true });
    ctx.session.username = user.username;
    ctx.helper.success({ ctx, res: user, msg: "登录成功" });
  }

  async show() {
    const { ctx, service } = this;
    // const username = ctx.cookies.get("username", { encrypt: true });
    // const userData = await service.user.findById(ctx.params.id);
    const { username } = ctx.session;
    if (!username) {
      return ctx.helper.error({ ctx, errorType: "loginValidateFail" });
    }
    ctx.helper.success({ ctx, res: username });
  }
}
